package com.weitu.accidentEvent.event.controller;

import com.weitu.accessory.bean.AccessoryPackageInfo;
import com.weitu.accessory.service.AccessoryUtilService;
import com.weitu.accessory.util.AccessoryUtil;
import com.weitu.accidentEvent.event.service.EventService;
import com.weitu.base.controller.BaseController;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.user.entity.User;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.workflow.flowBusiness.constant.FlowBusinessConstants;
import com.weitu.workflow.flowManagement.entity.WorkflowReview;
import com.weitu.workflow.flowManagement.service.FlowManagementService;
import org.fireflow.engine.IProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * Created by fanyuting on 2017/5/20 0020.
 */
@Controller
@RequestMapping("accidentEvent/event")
public class EventController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "accidentEvent/event/";
    @Autowired
    private AccessoryUtilService accessoryUtilService;//附件
    @Autowired
    private EventService eventService;
    @Autowired
    private FlowManagementService flowManagementService;//流程管理service
    private WorkflowReview workflowReview;

    public WorkflowReview getWorkflowReview() {
        return workflowReview;
    }

    /**
     * 跳转到事件管理页面
     *
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String toEventListPage(Model model) {
        return MODULE_BATH_PATH + "list";
    }

    /**
     * 查询事件报告列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("queryListByParam")
    public Object queryListByParam(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        //获取前台参数
        putParametersIntoMap(map);
        Integer totalNum = this.eventService.queryListCountByParam(map);//获取总数
        DataGridPagination pagination = DataGridPagination.getInstance(request, totalNum);
        PageView pageView = pagination.getPageView();//生成pageView分页对象
        map.put("pageView", pageView);
        List<Map<String, Object>> list = this.eventService.queryListByParam(map);
        return pagination.flushDataGridData(list);
    }

    /**
     * 跳转到事件报告新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping("add")
    public String toEventAddPage(Model model) {
        return MODULE_BATH_PATH + "add";
    }

    /**
     * 跳转到事件报告编辑页面
     *
     * @param model
     * @return
     */
    @RequestMapping("edit")
    public String toEventEditPage(Model model) {
        String businessId = this.getPara("businessId");
        Map<String, Object> info = this.eventService.queryInfoById(businessId);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        model.addAttribute("accessoryList", accessoryList);
        model.addAttribute("info", info);
        return MODULE_BATH_PATH + "edit";
    }

    /**
     * 跳转到事件报告详情页面
     *
     * @param model
     * @return
     */
    @RequestMapping("detail")
    public String toEventDetailPage(Model model) {
        String businessId = this.getPara("businessId");
        Map<String, Object> info = this.eventService.queryInfoById(businessId);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        model.addAttribute("accessoryList", accessoryList);
        model.addAttribute("info", info);
        return MODULE_BATH_PATH + "detail";
    }

    /**
     * 事件报告新增
     *
     * @param request
     * @return
     */
    @RequestMapping("addEventInfo")
    @ResponseBody
    public AjaxResult addEventInfo(HttpServletRequest request) {
        Map<String, Object> map = new HashMap();
        getAddBasicFieldMap(map);
        boolean accFlag = false;
        boolean flag = this.eventService.addInfo(map);
        if (flag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        if (accFlag) {
            return success("事件信息保存成功！");
        }
        return fail("事件信息保存失败！");
    }

    /**
     * 事件报告编辑
     *
     * @param request
     * @return
     */
    @RequestMapping("editEventInfo")
    @ResponseBody
    public AjaxResult editEventInfo(HttpServletRequest request) {
        Map<String, Object> map = new HashMap();
        getEditBasicFieldMap(map);
        boolean accFlag = false;
        boolean flag = this.eventService.editInfo(map);
        if (flag) {
            accFlag = AccessoryUtil.saveAccerssoryInfo(map.get("id").toString());
        }
        if (accFlag) {
            return success("事件信息保存成功！");
        }
        return fail("事件信息保存失败！");
    }

    /**
     * 事件报告删除
     *
     * @param request
     * @return
     */
    @RequestMapping("deleteEventInfo")
    @ResponseBody
    public AjaxResult deleteEventInfo(HttpServletRequest request) {
        String businessId = this.getPara("businessId");
        boolean flag = this.eventService.deleteInfo(businessId);
        if (flag) {
            return success("事件信息删除成功！");
        }
        return fail("事件信息删除失败！");
    }

     /*==============业务审批流程相关controller=======================*/

    /**
     * 提交审批
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "submitApplication", method = RequestMethod.POST)
    public AjaxResult submitApplication(HttpServletRequest request) throws Exception {
        User crrentUser = this.getSessionUser();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        AjaxResult result = new AjaxResult();
        putParametersIntoMap(paramMap);

        String businessId = paramMap.get("id").toString();//业务id
        String nextUserId = paramMap.get("nextUserId").toString();//下一环节审批人id
        //获取事故信息
        //Accident info = this.accidentService.queryInfoById(businessId);
        // LeaveApplication leaveApplication=this.leaveApplicationService.queryLeaveApplicationInfoById(leaveApplicationId);
        //启动流程实例
        IProcessInstance processInstance = this.flowManagementService.flowCreateAndRun(FlowBusinessConstants.BUSINESS_AE_EVENT, businessId, "事故信息登记", nextUserId);
        //int i=1/0;
        boolean appStateFlag = false;
        if (processInstance != null) {
            appStateFlag = this.eventService.editAppState(businessId, "0");
        }

        if (appStateFlag) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }

    /***
     * 跳转到信息审批页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toApplicationVerify")
    public ModelAndView toApplicationVerify(HttpServletRequest request) {
        User crrentUser = this.getSessionUser();
        ModelAndView modelAndView = new ModelAndView();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //获取参数
        putParametersIntoMap(paramMap);
        String businessId = paramMap.get("businessId").toString();//获取业务id，以businessId命名
        //工作项id
        String workItemId = paramMap.get("workItemId").toString();
        //表单类型；0：只读表单；1：编辑表单
        int formType = paramMap.get("formType") != null ? Integer.parseInt(paramMap.get("formType").toString()) : 0;
        modelAndView.addObject("workItemId", workItemId);
        modelAndView.addObject("formType", formType);

        //获取意见信息
        WorkflowReview workflowReview = this.flowManagementService.queryWorkflowReviewByWorkItemId(workItemId);
        modelAndView.addObject("workflowReview", workflowReview);

        //查询事故信息
        Map<String, Object> info = this.eventService.queryInfoById(businessId);
        //查询该业务对应的附件信息
        List<AccessoryPackageInfo> accessoryList = accessoryUtilService.queryAccessoryByBusinessId(businessId);
        //步骤：第几步信息
        String step = request.getParameter("step");
        modelAndView.addObject("step", step);
        modelAndView.addObject("info", info);
        modelAndView.addObject("accessoryList", accessoryList);
        modelAndView.addObject("uploadUserId", crrentUser.getId());
        modelAndView.setViewName(MODULE_BATH_PATH + "verify");
        return modelAndView;
    }

    /**
     * 审批信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "verifyApplication")
    public AjaxResult verifyApplication(HttpServletRequest request) throws Exception {
        String businessId = request.getParameter("businessId");
        String workItemId = request.getParameter("workItemId");//获取工作项id
        //查询处理结果及意见
        WorkflowReview workflowReview = this.flowManagementService.getWorkflowReviewByRequest(request, "workflowReview", workItemId);
        //保存处理结果
        boolean boo = this.flowManagementService.saveWorkflowReview(workflowReview);
        //步骤：第几步信息
        String step = request.getParameter("step");
        //结束环节，继续流程向下执行
        if (boo) {
            //更改业务中的审批状态
            String result = workflowReview.getResult();
            if ("1".equals(result)) {
                if ("2".equals(step)) {
                    this.eventService.editAppState(businessId, "1");
                }
            } else {
                if ("2".equals(step)) {
                    this.eventService.editAppState(businessId, "-1");
                }

            }

            this.flowManagementService.workItemComplete(workItemId);
        }
        //打印工作流信息
        //System.out.println(workflowReview.getComments());

        AjaxResult result = new AjaxResult();
        if (boo) {
            result.setMessage("提交成功！");
            result.setSuccess(true);
        } else {
            result.setMessage("提交失败！");
            result.setSuccess(false);
        }
        return result;
    }
}
